﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Attendences.Framework.BusinessLogic;
using Attendences.Framework.Entity;
using Wicresoft.Common;

public partial class Page_AttendencesList : BaseAuthenticationPage
{  
    public string SearchClauseList
    {
        get
        {
            if (ViewState["SearchClauseList"] == null)
                ViewState["SearchClauseList"] = "1=1";
            return ViewState["SearchClauseList"].ToString();
        }
        set
        {
            ViewState["SearchClauseList"] = value;
        }
    }
    public bool Manage
    {
        get
        {
            if (!string.IsNullOrEmpty(Request["Manage"]) && Request["Manage"].ToLower() == "false")
                return false;
            return true; 
        }
    }
    public string SearchClauseItem
    {
        get
        {
            if (ViewState["SearchClauseItem"] == null)
                ViewState["SearchClauseItem"] = "1=1";
            return ViewState["SearchClauseItem"].ToString();
        }
        set
        {
            ViewState["SearchClauseItem"] = value;
        }
    }

    protected DataTable AttendList
    {
        get
        {
            if (ViewState["AttendList"] == null)
                ViewState["AttendList"] = new DataTable();
            return ViewState["AttendList"] as DataTable;
        }
        set
        {
            ViewState["AttendList"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.Title = "值班列表";

        this.tbSearchDate.Attributes.Add("readonly", "true");


        trAdd.Visible = Manage;
        if (!IsPostBack)
        {
            this.Order.OrderColumn = "CreateTime";
            this.Order.OrderDirection = "DESC";

            for (int i = 0; i < 24; i++)
            {
                ddlStartHour.Items.Add(i.ToString("D2"));
                ddlEndHour.Items.Add(i.ToString("D2"));
            }
            for (int i = 0; i < 60; i++)
            {
                ddlStartMinute.Items.Add(i.ToString("D2"));
                ddlEndMinute.Items.Add(i.ToString("D2"));
            }
            ddlStartHour.Items.Insert(0, "全部");
            ddlEndHour.Items.Insert(0, "全部");
            BindData();
            
        }
        
    }

    protected override void Pager_PageChanged(object sender, EventArgs e)
    {
        BindData();
        base.Pager_PageChanged(sender, e);
    }

    protected override void Order_OrderChanged(object sender, EventArgs e)
    {
        BindData();
        base.Order_OrderChanged(sender, e);
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        BindData();
    }

    protected void lbtnDelete_Click(object sender, EventArgs e)
    {
       
        ArrayList alAttendList = new ArrayList();

        int deleteCount = 0;
        for (int i = 0; i < rptAttendences.Items.Count; i++)
        {
            if ((rptAttendences.Items[i].FindControl("cbAttendences") as CheckBox).Checked)
            {
                int id =(int)AttendList.Rows[rptAttendences.Items[i].ItemIndex][Attendence.SQLCOL_ID];
                alAttendList.Add(id);
                deleteCount++;
            }
        }
        //对选定的表Attendence中的ID集合予以全部删除
        BLAttendences.DeleteAttendencesList((int[])alAttendList.ToArray(typeof(int)));
        int pageCount = (Pager.RecordCount + Pager.PageSize - 1) / Pager.PageSize;
        if ((Pager.RecordCount - 1) / Pager.PageSize != (Pager.RecordCount - 1 - deleteCount) / Pager.PageSize && Pager.PageSize > 0 && (Pager.PageIndex == pageCount - 1))
            Pager.PageIndex--;

        BindData();    
    }

    private void BindData()
    {
        int recordCount =  DataAccess.ExecuteSql("Attendences.ConnectionString","select distinct attendenceid from View_Attend_All where "+SearchClauseList).Tables[0].Rows.Count;
        int selectRows = Math.Min(recordCount, Pager.PageSize * (Pager.PageIndex + 1));
        int CurrentPageRows = Math.Min(Pager.PageSize, selectRows - Pager.PageSize * Pager.PageIndex);
        string Order = string.Format("{0} {1}", this.Order.OrderColumn, this.Order.OrderDirection);
        string DESCOrder = string.Format("{0} {1}", this.Order.OrderColumn, this.Order.OrderDirection.ToLower()=="asc"?"DESC":"ASC");
        string sql = string.Format(@"SELECT *
                                     FROM
                                         (SELECT Top {0} * 
                                          FROM
                                            (SELECT Top {1}    attendenceID as ID,Name,Place,CreateTime,IsShutDown,Max(attendDate) as MaxAttendDate,min(attendDate) as MinAttendDate
                                             FROM  View_Attend_All
                                             GROUP BY attendenceID,Name,Place,CreatetIme,IsShutDown
                                             ORDER BY {2}) a 
                                          ORDER BY {3}) b 
                                     ORDER BY {2}",CurrentPageRows,selectRows,Order,DESCOrder);
        AttendList = DataAccess.ExecuteSql("Attendences.ConnectionString", sql).Tables[0];
        Pager.RecordCount = recordCount;
        rptAttendences.DataSource =AttendList;
        rptAttendences.DataBind();
    }

    protected void btnAdvancedSearch_Click(object sender, EventArgs e)
    {
        SearchClauseItem = "1=1";
        if (tbSearchDate.Text != string.Empty)
            SearchClauseItem += string.Format("AND {0} = '{1}'", View_Attend_All.SQLCOL_ATTENDDATE, tbSearchDate.Text);
        if (ddlStartHour.SelectedValue != "全部")
        {
            if (string.IsNullOrEmpty(tbSearchDate.Text))
            {
                ClientScript.RegisterStartupScript(GetType(), "wrong", "<script>alert('必须填写日期才可以根据时间查询')</script>");
                return;
            }
            SearchClauseItem += string.Format(" AND {0}>=N'{1}'", View_Attend_All.SQLCOL_ATTENDTIMESTART, tbSearchDate.Text + " " + ddlStartHour.SelectedValue + ":" + ddlStartMinute.SelectedValue + ":00");
        }
        if (ddlEndHour.SelectedValue != "全部")
        {
            if (string.IsNullOrEmpty(tbSearchDate.Text))
            {
                ClientScript.RegisterStartupScript(GetType(), "wrong", "<script>alert('必须填写日期才可以根据时间查询')</script>");
                return;
            }
            SearchClauseItem += string.Format(" AND {0}<=N'{1}'", View_Attend_All.SQLCOL_ATTENDTIMEEND, tbSearchDate.Text + " " + ddlEndHour.SelectedValue + ":" + ddlEndMinute.SelectedValue + ":00");
        }
        if (tbSearchUserDisplayName.Text != string.Empty)
            SearchClauseItem += string.Format(" AND {0} LIKE N'%{1}%'", View_Attend_All.SQLCOL_USERDISPLAYNAME, tbSearchUserDisplayName.Text.Replace("'", "''").Replace("%", "[%]"));

        SearchClauseList = "1=0"; 
        DataTable searchAttendItem = new DataTable();
        searchAttendItem = DataAccess.Select(typeof(View_Attend_All), SearchClauseItem);
        for(int i=0;i<searchAttendItem.Rows.Count;i++)
        {
            //drItem["AttendenceID"] = drItem[AttendenceItem.SQLCOL_ATTENDENCEID];
            int id=(int)searchAttendItem.Rows[i][AttendenceItem.SQLCOL_ATTENDENCEID];
            SearchClauseList += string.Format("OR {0}={1}", Attendence.SQLCOL_ID, id);
        }

        tbSearchDate.Text = string.Empty;
        tbSearchUserDisplayName.Text = string.Empty;
        BindData();
    }
}

